"""
腾讯云COS工具类 - 适配像素项目
"""
import uuid
from datetime import datetime
from qcloud_cos import CosConfig, CosS3Client
from django.conf import settings


class COSUploader:
    """腾讯云COS上传工具"""
    
    def __init__(self):
        config = settings.TENCENT_COS_CONFIG
        self.secret_id = config.get('SECRET_ID') or ''
        self.secret_key = config.get('SECRET_KEY') or ''
        self.region = config.get('REGION') or ''
        self.bucket = config.get('BUCKET') or ''
        self.domain = config.get('DOMAIN') or ''
        self.folder = config.get('FOLDER') or 'xiangsu'
        self.enabled = all([self.secret_id, self.secret_key, self.region, self.bucket, self.domain])
        self.client = None
        if self.enabled:
            try:
                cos_config = CosConfig(Region=self.region, SecretId=self.secret_id, SecretKey=self.secret_key)
                self.client = CosS3Client(cos_config)
            except Exception:
                self.enabled = False
                self.client = None
    
    def generate_file_path(self, filename, file_type='avatar', user_id=None):
        """
        生成唯一的文件路径
        
        Args:
            filename: 原始文件名
            file_type: 文件类型 (avatar, image, etc.)
            user_id: 用户ID（可选）
            
        Returns:
            生成的文件路径，格式: folder/file_type/user_id/YYYYMMDD/uuid_filename
        """
        # 提取文件扩展名
        ext = filename.split('.')[-1] if '.' in filename else ''
        
        # 生成日期文件夹
        date_folder = datetime.now().strftime('%Y%m%d')
        
        # 生成唯一文件名
        unique_filename = f"{uuid.uuid4().hex[:8]}_{filename}"
        
        # 构建路径
        if user_id:
            file_path = f"{self.folder}/{file_type}/user_{user_id}/{date_folder}/{unique_filename}"
        else:
            file_path = f"{self.folder}/{file_type}/{date_folder}/{unique_filename}"
        
        return file_path
    
    def upload_file(self, file_obj, file_path=None, file_type='avatar', user_id=None):
        """
        上传文件到COS
        
        Args:
            file_obj: Django上传的文件对象
            file_path: 指定的文件路径（可选，不指定则自动生成）
            file_type: 文件类型
            user_id: 用户ID
            
        Returns:
            dict: {
                'success': bool,
                'url': str,  # 文件的完整访问URL
                'path': str,  # 文件在COS中的路径
                'message': str
            }
        """
        try:
            if not self.enabled or not self.client:
                return {'success': False, 'url': '', 'path': '', 'message': 'COS未配置'}
            if not file_path:
                file_path = self.generate_file_path(file_obj.name, file_type, user_id)
            response = self.client.put_object(Bucket=self.bucket, Body=file_obj.read(), Key=file_path, EnableMD5=False)
            file_url = f"{self.domain}/{file_path}"
            return {'success': True, 'url': file_url, 'path': file_path, 'message': '上传成功'}
        except Exception as e:
            return {'success': False, 'url': '', 'path': '', 'message': f'上传失败: {str(e)}'}
    
    def delete_file(self, file_path):
        """
        删除COS中的文件
        
        Args:
            file_path: 文件在COS中的路径
            
        Returns:
            dict: {'success': bool, 'message': str}
        """
        try:
            if not self.enabled or not self.client:
                return {'success': False, 'message': 'COS未配置'}
            self.client.delete_object(Bucket=self.bucket, Key=file_path)
            return {'success': True, 'message': '删除成功'}
        except Exception as e:
            return {'success': False, 'message': f'删除失败: {str(e)}'}


# 全局COS上传器实例
cos_uploader = COSUploader()
